<template>
  <div>
    <h1>级联选择器</h1>
    <el-cascader :options="options.list" />
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'

const options = reactive({
  list: []
})

const listData = [
  {
    id: 1,
    text: '节点1',
    parentId: 0 // 0 顶级节点
  },
  {
    id: 2,
    text: '节点1-1',
    parentId: 1 // 通过这个字段来确定子父级
  },
  {
    id: 3,
    text: '节点1-2',
    parentId: 1
  },
  {
    id: 4,
    text: '节点1-1-1',
    parentId: 2
  },
  {
    id: 5,
    text: '节点1-2-1',
    parentId: 3
  },
  {
    id: 6,
    text: '节点2',
    parentId: 0
  },
  {
    id: 7,
    text: '节点2-1',
    parentId: 6
  },
  {
    id: 8,
    text: '节点2-2',
    parentId: 6
  },
  {
    id: 9,
    text: '节点3',
    parentId: 0
  }
]

let pid = 0,
  pidFiled = 'parentId',
  labelFiled = 'text',
  valueFiled = 'id'
// 构建一个内部函数，用于实现递归
const makeTree = (pid, arr) => {
  const res = []
  arr.forEach(item => {
    if (item[pidFiled] === pid) {
      // 自己调用自己，递归查归属于自己的 children
      const children = makeTree(item[valueFiled], listData)
      // 将原有的数据按照 element 的格式进行重构
      const obj = {
        label: item[labelFiled],
        value: item[valueFiled]
      }
      // 如果有 children 则插入 obj 中
      if (children.length) {
        console.log(' obj.children ', obj.children)
        obj.children = children
        console.log(' obj.children ', obj.children)
      }
      console.log('obj', obj)
      res.push(obj)
      console.log('res', res)
    }
  })
  console.log('res............', res)
  return res
}

options.list = makeTree(pid, listData)
</script>

<style lang="scss" scoped></style>
